package com.macro.mall.utils;

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class MsgDecrypt {
    public static String decrypt(String text, String encodingAesKey) throws Exception {
        byte[] aesKey = Base64.decodeBase64(encodingAesKey + "=");
        SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
        IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
        byte[] decrypted = cipher.doFinal(Base64.decodeBase64(text));
        byte[] plaintext = PKCS7Decoder.decode(decrypted);

        byte[] networkOrder = Arrays.copyOfRange(plaintext, 16, 20);
        int msgLength = recoverNetworkBytesOrder(networkOrder);

        return new String(
            Arrays.copyOfRange(plaintext, 20, 20 + msgLength),
            StandardCharsets.UTF_8
        );
    }

    private static int recoverNetworkBytesOrder(byte[] orderBytes) {
        return (orderBytes[0] << 24) |
               ((orderBytes[1] & 0xff) << 16) |
               ((orderBytes[2] & 0xff) << 8) |
               (orderBytes[3] & 0xff);
    }
}
